<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>{{ isEdit ? '编辑用户' : '新增用户' }}</h3>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        label-position="right"
        status-icon
        v-loading="loading"
      >
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="用户名" prop="username">
              <el-input 
                v-model="form.username" 
                placeholder="请输入用户名" 
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="工号" prop="staffId">
              <el-input v-model="form.staffId" placeholder="请输入工号，留空则自动生成" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" value="active" />
                <el-option label="禁用" value="inactive" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">角色与部门</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="角色" prop="role">
              <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
                <el-option 
                  v-for="item in roleOptions" 
                  :key="item.name" 
                  :label="item.displayName || item.name" 
                  :value="item.name" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="部门" prop="departmentId">
              <el-select 
                v-model="form.departmentId" 
                placeholder="请选择部门" 
                style="width: 100%"
                clearable
                filterable
                :loading="loading"
              >
                <el-option 
                  v-for="item in departmentOptions" 
                  :key="item.id" 
                  :label="item.name" 
                  :value="item.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left" v-if="!isEdit">密码</el-divider>
        
        <el-row :gutter="20" v-if="!isEdit">
          <el-col :span="8">
            <el-form-item label="密码" prop="password">
              <el-input 
                v-model="form.password" 
                placeholder="请输入密码" 
                show-password
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="form.confirmPassword" 
                placeholder="请再次输入密码" 
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <div class="form-actions">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">提交</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { userAPI, roleAPI, departmentAPI } from '@/utils/api'

const router = useRouter()
const route = useRoute()
const userId = ref(route.params.id)
const isEdit = computed(() => !!userId.value)

// 表单数据
const formRef = ref(null)
const loading = ref(false)
const submitting = ref(false)

// 下拉选项
const roleOptions = ref([])
const departmentOptions = ref([])

// 表单数据
const form = reactive({
  username: '',
  name: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  role: '',
  departmentId: '',
  staffId: '',
  status: 'active'
})

// 验证两次密码是否一致
const validatePassword = (rule, value, callback) => {
  if (value !== form.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 根据是否是编辑模式动态设置密码验证规则
if (!isEdit.value) {
  rules.password = [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
  ]
  rules.confirmPassword = [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ]
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const res = await roleAPI.getRoles()
    console.log('角色列表API响应:', res)
    
    // 处理不同的响应格式
    if (res.success) {
      roleOptions.value = res.data.roles || []
    } else if (res.data && res.data.success) {
      roleOptions.value = res.data.data.roles || []
    } else {
      console.error('获取角色列表失败：响应格式不正确', res)
    }
  } catch (error) {
    console.error('获取角色列表失败', error)
  }
}

// 获取部门列表
const fetchDepartments = async () => {
  try {
    console.log('开始获取部门列表...')
    loading.value = true
    
    // 清空部门选项，确保不会显示旧数据
    departmentOptions.value = []
    
    const res = await departmentAPI.getAllDepartments()
    console.log('部门列表API响应:', res)
    
    if (res.success && res.data) {
      // 使用新的API响应格式
      const departments = res.data
      
    if (departments && departments.length > 0) {
        departmentOptions.value = departments.map(dept => ({
          id: dept.id || dept._id || '',
            name: dept.name || '未命名部门',
            code: dept.code || '',
          category: dept.category || ''
        }))
      
      console.log('处理后的部门选项:', departmentOptions.value)
    } else {
      console.warn('未获取到任何部门数据')
      departmentOptions.value = []
      }
    } else {
      console.error('获取部门列表失败：响应格式不符合预期', res)
      ElMessage.warning('获取部门数据失败，请刷新页面重试')
    }
  } catch (error) {
    console.error('获取部门列表失败', error)
    ElMessage.error('获取部门列表失败，请刷新页面重试')
    departmentOptions.value = []
  } finally {
    loading.value = false
  }
}

// 获取用户详情
const fetchUserDetail = async () => {
  if (!userId.value) return
  
  loading.value = true
  try {
    const res = await userAPI.getUser(userId.value)
    console.log('用户详情API响应:', res)
    
    // 处理不同的响应格式
    let userData = null
    
    if (res.success) {
      userData = res.data.user
    } else if (res.data && res.data.success) {
      userData = res.data.data.user
    } else {
      ElMessage.error('获取用户详情失败：响应格式不正确')
      console.error('响应格式不正确:', res)
      return
    }
    
    if (userData) {
      // 填充表单数据
      Object.keys(form).forEach(key => {
        if (key !== 'password' && key !== 'confirmPassword' && userData[key] !== undefined) {
          form[key] = userData[key]
        }
      })
      
      // 处理状态值，确保与前端显示一致
      if (form.status === '启用') {
        form.status = 'active'
      } else if (form.status === '禁用') {
        form.status = 'inactive'
      }
    } else {
      ElMessage.error('获取用户详情失败：用户数据为空')
    }
  } catch (error) {
    console.error('获取用户详情失败', error)
    ElMessage.error('获取用户详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      // 准备提交的数据
      const userData = { ...form }
      // 移除确认密码字段
      delete userData.confirmPassword
      
      // 如果是编辑模式且没有设置密码，则删除密码字段
      if (isEdit.value) {
        delete userData.password
      }
      
      // 处理status字段，确保与后端期望的格式一致
      if (userData.status === '启用') {
        userData.status = 'active'
      } else if (userData.status === '禁用') {
        userData.status = 'inactive'
      }
      
      // 确保departmentId为有效值或null
      if (!userData.departmentId || userData.departmentId === '') {
        delete userData.departmentId
      } else {
        // 确保departmentId是字符串类型
        userData.departmentId = String(userData.departmentId)
      }
      
      // 确保其他字段符合后端要求
      if (userData.phone && !/^\d{11}$/.test(userData.phone)) {
        ElMessage.warning('手机号格式不正确，请输入11位数字')
        submitting.value = false
        return
      }
      
      console.log('提交的用户数据:', userData)
      
      let res
      if (isEdit.value) {
        res = await userAPI.updateUser(userId.value, userData)
      } else {
        res = await userAPI.createUser(userData)
      }
      
      console.log(isEdit.value ? '更新用户响应:' : '创建用户响应:', res)
      
      // 处理不同的响应格式
      let success = false
      let message = ''
      
      if (res.success) {
        success = true
      } else if (res.data && res.data.success) {
        success = true
      } else if (res.data && res.data.message) {
        message = res.data.message
      } else if (res.message) {
        message = res.message
      }
      
      if (success) {
        ElMessage.success(isEdit.value ? '用户更新成功' : '用户创建成功')
        goBack()
      } else {
        ElMessage.error(message || (isEdit.value ? '用户更新失败' : '用户创建失败'))
      }
    } catch (error) {
      console.error(isEdit.value ? '用户更新失败' : '用户创建失败', error)
      if (error.response && error.response.data) {
        console.error('错误详情:', error.response.data)
        if (error.response.data.errors) {
          const errorMessages = Object.entries(error.response.data.errors)
            .map(([field, msgs]) => `${field}: ${msgs.join(', ')}`)
            .join('; ')
          ElMessage.error(`验证失败: ${errorMessages}`)
        } else {
          ElMessage.error(error.response.data.message || (isEdit.value ? '用户更新失败' : '用户创建失败'))
        }
      } else {
        ElMessage.error(isEdit.value ? '用户更新失败' : '用户创建失败')
      }
    } finally {
      submitting.value = false
    }
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 生命周期钩子
onMounted(() => {
  fetchRoles()
  fetchDepartments()
  
  if (isEdit.value) {
    fetchUserDetail()
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  gap: 20px;
}
</style> 